package cn.stylefeng.guns.sys.core.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉字转换为拼音
 */
public class PinYinUtil {
    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        //转为首字母大写
        System.out.println(getPinYinCode("汉字转换、为拼音").toUpperCase());
        System.out.println(getPinYinAllCode("汉字转换、为拼音"));
    }

    /**
     * 获取大写首字母，如果有英文字母，原样输出
     *
     * @param chinese
     * @return
     */
    public static String getPinYinCode(String chinese) {
        return getPinYinCodeLowerCase(chinese).toUpperCase();
    }


    /**
     * 获取字符串拼音的第一个字母
     *
     * @param chinese
     * @return
     */
    public static String getPinYinCodeLowerCase(String chinese) {
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();  //转为单个字符
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    String[] pyarr = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat);
                    if(pyarr == null){
                        continue;
                    }
                    pinyinStr += pyarr[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

    /**
     * 汉字转为拼音
     *
     * @param chinese
     * @return
     */
    public static String getPinYinAllCode(String chinese) {
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    String[] zhz = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat);
                    if(zhz!=null){
                        pinyinStr += zhz[0];
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

}